<template>
	<view class="makeimg">
		<u-navbar
			title="营销图制作"
			:back-icon-size="28"
			back-icon-color="#000000"
			:title-size="28"
			:border-bottom="false"
			:back-text-style="{ color: '#000000', fontSize: '26rpx' }"
			title-color="#000000"
			:custom-back="goback"
			:background="{ background: '#ffffff' }"
		></u-navbar>
		<view class="uploadbox">
			<view class="canvas_box" v-if="createurl == ''">
				<view class="uptop">
					<u-upload
						class="upload1"
						:action="action"
						:width="706"
						:height="724"
						:file-list="fileList"
						:index="1"
						@on-error="uploaderr"
						@on-success="doupland"
						:max-count="1"
						:show-progress="false"
						:deletable="isdelshow"
						:max-size="5 * 1024 * 1024"
						:limitType="['png', 'jpg', 'jpeg', 'webp']"
					></u-upload>
					<view class="uptop_img">
						<u-image :width="710" mode="widthFix" :height="96" src="//img.letuilm.com/2020/09/e39ab7202009281523498020.png"></u-image>
						<view class="up_text">
							<view class="coupon">{{ after_coupon }}</view>
							<view class="brand">{{ brand }}</view>
							<view class="coupon_price">{{ coupon_price }}</view>
						</view>
					</view>
				</view>
				<view class="upbot">
					<u-upload
						class="upload2"
						:action="action"
						:width="353"
						:height="362"
						:file-list="fileList"
						:index="2"
						@on-error="uploaderr"
						@on-success="doupland"
						:max-count="1"
						:deletable="isdelshow"
						:show-progress="false"
						:max-size="5 * 1024 * 1024"
						:limitType="['png', 'jpg', 'jpeg', 'webp']"
					></u-upload>
					<u-upload
						class="upload3"
						:action="action"
						:width="353"
						:height="362"
						:file-list="fileList"
						:index="3"
						:deletable="isdelshow"
						@on-error="uploaderr"
						@on-success="doupland"
						:max-count="1"
						:show-progress="false"
						:max-size="5 * 1024 * 1024"
						:limitType="['png', 'jpg', 'jpeg', 'webp']"
					></u-upload>
				</view>
			</view>
			<view class="hah" v-else><image :src="createurl" style="width: 710rpx;height: 1090rpx;" @longtap="show = true"></image></view>
		</view>
		<view class="bot_c">
			<u-field v-model="after_coupon" label="券后价：" placeholder=""></u-field>
			<u-field v-model="brand" label="文字：" placeholder=""></u-field>
			<u-field v-model="coupon_price" label="券面值：" placeholder=""></u-field>

			<u-button
				v-if="createurl == ''"
				size="default"
				:ripple="true"
				:hair-line="true"
				:disabled="disabled"
				:custom-style="{
					width: '572rpx',
					height: '70rpx',
					color: disabled == true ? '#000000' : '#ffffff',
					backgroundColor: disabled == true ? '#ffffff' : '#FFDB28'
				}"
				@click="domake"
			>
				生成图片
			</u-button>
			<u-button
				v-else
				size="default"
				:ripple="true"
				:hair-line="true"
				:custom-style="{
					width: '572rpx',
					height: '70rpx',
					color: '#000000',
					backgroundColor: '#ffffff'
				}"
				@click="doclearimg"
			>
				重 置
			</u-button>
		</view>
		<view style="z-index: -99;position: absolute;top: 0;left: 0;"><canvas canvas-id="myCanvas" style="width: 710rpx;height: 1086rpx;backgroundColor: #FFFFFF"></canvas></view>
		<u-toast ref="uToast"></u-toast>
		<u-modal v-model="mshow" :content="content"></u-modal>
		<u-action-sheet :list="list" v-model="show" @click="dosave"></u-action-sheet>
	</view>
</template>

<script>
export default {
	name: 'makeimg',
	data() {
		return {
			list: [
				{
					text: '保存图片',
					color: 'black',
					fontSize: 28
				}
			],
			content: '图片生成成功，请长按图片进行保存。',
			show: false,
			mshow: false,
			createurl: '',
			lists: [],
			phoneWith: this.phoneWidth,
			disabled: true,
			uploadone: '',
			isdelshow: true,
			uploadtwo: '',
			uploadthree: '',
			after_coupon: '19.9',
			brand: '天猫Tmall',
			coupon_price: '60',
			action: 'https://app.letuilm.com/api/upload', //file
			fileList: [
				// {
				// 	url: 'http://pics.sc.chinaz.com/files/pic/pic9/201912/hpic1886.jpg'
				// }
			]
		};
	},
	watch: {
		uploadone: function(val) {
			// console.log(this.form.username);
			if (val !== '') {
				if (this.uploadtwo !== '' && this.uploadthree !== '') {
					this.disabled = false;
				}
			} else {
				this.disabled = true;
			}
		},
		uploadtwo: function(val) {
			// console.log(this.form.username);
			if (val !== '') {
				if (this.uploadone !== '' && this.uploadthree !== '') {
					this.disabled = false;
				}
			} else {
				this.disabled = true;
			}
		},
		uploadthree: function(val) {
			// console.log(this.form.username);
			if (val !== '') {
				if (this.uploadtwo !== '' && this.uploadone !== '') {
					this.disabled = false;
				}
			} else {
				this.disabled = true;
			}
		}
	},
	//实例创建完成后被立即调用
	created() {},
	onLoad(option) {
		var that = this;
	},
	//挂载开始之前被调用
	beforeMount() {},
	//  onPullDownRefresh() {
	//  //监听下拉刷新动作的执行方法，每次手动下拉刷新都会执行一次
	// console.log('refresh');
	// setTimeout(function() {
	// 	uni.stopPullDownRefresh(); //停止下拉刷新动画
	// }, 1000);
	//  },
	//初次渲染完成
	onReady() {
		// this.lists = this.$refs.uUpload.lists;
	},
	//全局只触发一次
	onLaunch() {},
	//从后台进入前台
	onShow() {},
	//前台进入后台
	onHide() {},
	methods: {
		doclearimg() {
			this.createurl = '';
		},
		dosave(index) {
			let that = this;
			// #ifdef  MP
			uni.downloadFile({
				url: this.createurl,
				success: res => {
					if (res.statusCode === 200) {
						// console.log('app', res.tempFilePath);
						uni.saveImageToPhotosAlbum({
							filePath: res.tempFilePath,
							success: res => {
								that.$refs.uToast.show({
									title: '保存成功',
									type: 'success'
								});
							},
							fail: err => {
								that.$refs.uToast.show({
									title: '保存失败',
									type: 'error'
								});
							}
						});
					}
				},
				fail: res => {
					uni.hideLoading();
					app.errornet('生成失败');
				}
			});
			// #endif

			// #ifdef APP-PLUS
			uni.getImageInfo({
				src: this.createurl,
				success(image) {
					console.log(image.path);
					uni.saveImageToPhotosAlbum({
						filePath: image.path,
						success: () => {
							that.$refs.uToast.show({
								title: '保存成功',
								type: 'success'
							});
						}
					});
				}
			});
			// #endif

			// #ifdef H5
			var canvas = document.createElement('canvas');
			var img = document.createElement('img');
			img.onload = function(e) {
				canvas.width = img.width;
				canvas.height = img.height;
				var context = canvas.getContext('2d');
				context.drawImage(img, 0, 0, img.width, img.height);
				canvas.getContext('2d').drawImage(img, 0, 0, img.width, img.height);
				canvas.toBlob(blob => {
					let link = document.createElement('a');
					link.href = window.URL.createObjectURL(blob);
					link.download = '';
					link.click();
					that.$refs.uToast.show({
						title: '保存成功',
						type: 'success'
					});
				}, 'image/jpeg');
			};
			img.setAttribute('crossOrigin', 'Anonymous');
			img.src = this.createurl;

			// #endif
		},
		domake() {
			this.isdelshow = false;
			let _this = this;
			let phoneWith = this.phoneWith;
			// let scale = (phoneWith * 0.9) / 940;
			let scale = 1;
			// console.log(scale);

			uni.showLoading({
				mask: true,
				title: '生成中...'
			});
			// console.log(this.uploadone, this.uploadtwo, this.uploadthree);
			// _this.downloadImages(this.uploadone, function(res) {
			let uploadone = this.uploadone;
			// console.log('uploadone', uploadone);
			// _this.downloadImages(this.uploadtwo, function(res) {
			let uploadtwo = this.uploadtwo;
			// _this.downloadImages(this.uploadthree, function(res) {
			let uploadthree = this.uploadthree;
			let after_coupon = this.after_coupon;
			let brand = this.brand;
			let coupon_price = this.coupon_price;
			_this.drawPost(
				'myCanvas',
				356 * scale,
				543 * scale,
				[
					{
						type: 'image',
						url: uploadone,
						x: 0,
						y: 0,
						width: 356 * scale,
						height: 362 * scale,
						isCircle: false
					},
					{
						type: 'image',
						url: uploadtwo,
						x: 0,
						y: 362 * scale,
						width: 178 * scale,
						height: 181 * scale,
						isCircle: false
					},
					{
						type: 'image',
						url: uploadthree,
						x: 178 * scale,
						y: 362 * scale,
						width: 178 * scale,
						height: 181 * scale,
						isCircle: false
					},
					{
						type: 'image',
						url: '/static/image/makeimg.png',
						x: 0,
						y: 314 * scale,
						width: 356 * scale,
						height: 48 * scale,
						isCircle: false
					},
					{
						type: 'text',
						text: after_coupon,
						textAlign: 'left',
						lineAlign: 'TOP',
						x: 25 * scale,
						y: 350 * scale,
						color: 'white',
						size: 30,
						bold: true
					},
					{
						type: 'text',
						text: brand,
						textAlign: 'left',
						lineAlign: 'TOP',
						x: 122 * scale,
						y: 350 * scale,
						color: 'white',
						size: 25,
						bold: true
					},
					{
						type: 'text',
						text: coupon_price,
						textAlign: 'left',
						lineAlign: 'TOP',
						x: 290 * scale,
						y: 350 * scale,
						color: 'black',
						size: 30,
						bold: true
					}
				],
				data => {
					// console.log(data);
					this.mshow = true;
				}
			);
			// 		});
			// 	});
			// });
		},
		// canvas绘画封装
		drawPost: function(id, width, height, options, callback) {
			const ctx = uni.createCanvasContext(id);
			let that = this;
			// console.log('ctx', ctx);
			for (let i = 0; i < options.length; i++) {
				let setting = options[i];
				if (setting.type == 'image') {
					if (setting.isCircle) {
						let x = setting.x + setting.width / 2;
						let y = setting.y + setting.height / 2;
						let r = setting.height / 2;
						ctx.save();
						ctx.beginPath();
						ctx.arc(x, y, r, 0, 2 * Math.PI);
						ctx.clip();
						ctx.drawImage(setting.url, setting.x, setting.y, setting.width, setting.height);
						ctx.restore();
					} else {
						ctx.drawImage(setting.url, setting.x, setting.y, setting.width, setting.height);
					}
				} else if (setting.type == 'text') {
					let text = setting.text;
					ctx.setFontSize(setting.size);
					ctx.setFillStyle(setting.color);
					if (text.length > 17) {
						let s_text = text.slice(0, 17);
						let e_text = text.slice(17);
						ctx.fillText(s_text, setting.x, setting.y);
						ctx.fillText(e_text, setting.x, setting.y + 23);
					} else {
						ctx.fillText(setting.text, setting.x, setting.y);
					}
				} else if (setting.type == 'line') {
					ctx.setFillStyle(setting.color);
					ctx.setStrokeStyle(setting.color);
					ctx.moveTo(setting.x, setting.y);
					ctx.lineTo(setting.x + setting.width, setting.y);
					ctx.stroke();
				}
			}
			ctx.draw(true, function(e) {
				// console.log('e', e);
				uni.hideLoading();
				setTimeout(() => {
					uni.canvasToTempFilePath({
						x: 0,
						y: 0,
						width: width,
						height: height,
						quality: 1,
						canvasId: id,
						success: function(respon) {
							uni.hideLoading();
							// console.log('生成成功!', respon.tempFilePath);
							that.createurl = respon.tempFilePath;
							callback(respon.tempFilePath);
						},
						fail: function(res) {
							uni.hideLoading();
							uni.showToast({
								title: '生成失败',
								icon: 'none'
							});
						}
					});
				}, 200);
			});
		},
		// 缓存本地
		downloadImages: function(url, callback) {
			uni.downloadFile({
				url: url,
				success: res => {
					// console.log('downloadFile', res);
					if (res.statusCode === 200) {
						callback(res.tempFilePath);
					}
				},
				fail: res => {
					uni.hideLoading();
					app.errornet('生成失败');
				}
			});
		},
		goback() {
			uni.navigateBack({
				delta: 1,
				animationType: 'pop-out',
				animationDuration: 200
			});
		},
		doupland(data, index, lists, name) {
			// console.log('上传成功返回', data, index, lists, name);
			if (data.code == 200) {
				// lists[0].url = `//` + data.data.url;
				switch (name) {
					case 1:
						// this.uploadone = '//' + data.data.url;
						this.uploadone = lists[0].url;
						break;
					case 2:
						// this.uploadtwo = '//' + data.data.url;
						this.uploadtwo = lists[0].url;
						break;
					case 3:
						// this.uploadthree = '//' + data.data.url;
						this.uploadthree = lists[0].url;
						break;
					default:
						break;
				}
			}
		},
		uploaderr(res, index, lists, name) {
			console.log('上传错误返回', res, index, lists, name);
		}
	}
};
</script>

<style lang="scss" scoped>
.makeimg {
	background-color: #ffffff;
	.uploadbox {
		width: 710rpx;
		margin: 0 auto;
		.canvas_box::v-deep {
			border: 2rpx solid #bbbbbb;
			overflow: hidden;
			.u-preview-image {
				border-radius: 0;
			}
			.u-list-item {
				border-radius: 0;
			}
			.uptop {
				position: relative;
				.upload1 {
					.u-list-item {
						// width: 690rpx !important;
						margin: 0;
						background-color: #ffffff;
					}
				}
				.uptop_img {
					position: absolute;
					bottom: -6rpx;
					.up_text {
						position: absolute;
						bottom: 4rpx;
						width: 100%;
						display: flex;
						justify-content: space-around;
						align-items: center;
						height: 90rpx;
						line-height: 90rpx;
						z-index: 2;
						text-align: center;
						font-weight: 600;
						font-size: 40rpx;
						color: white;
						.coupon {
							width: 122rpx;
							font-size: 50rpx;
						}
						.brand {
							width: 196rpx;
							margin-right: 20rpx;
						}
						.coupon_price {
							width: 106rpx;
							color: #000000;
							font-size: 55rpx;
						}
					}
				}
			}
			.upbot {
				display: flex;
				.upload2 {
					.u-list-item {
						// width: 690rpx !important;
						margin: 0;
						background-color: #ffffff;
					}
				}
				.upload3 {
					border-left: 2rpx solid #bbbbbb;
					.u-list-item {
						// width: 690rpx !important;
						margin: 0;
						background-color: #ffffff;
					}
				}
			}
		}
	}
	.bot_c {
		padding-bottom: 30rpx;
	}
	/* #ifdef H5 */
	.hah::v-deep {
		div {
			display: none;
		}
		img {
			opacity: 1;
		}
	}
	/* #endif */
}
</style>
